package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: 祺诺
 * @Name; xqf
 * @Date: 2021/1/3 20:41
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        if (requestURI.endsWith("LoginStudentServlet")||requestURI.endsWith("login.jsp")){
            filterChain.doFilter(req,resp);
            return;
        }
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if (user==null){
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else {
            filterChain.doFilter(req,resp);
            return;
        }
    }
}
